package com.bit.cfdi.web.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bit.cfdi.web.dao.TelefonoDAO;
import com.bit.cfdi.web.domain.Contacto;
import com.bit.cfdi.web.domain.Telefono;

@Repository
public class TelefonoDAOImpl extends HibernateDaoSupport implements TelefonoDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
	}
	
	@Override
	@Transactional public void save(Telefono telefono) {
		getHibernateTemplate().saveOrUpdate(telefono);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public Telefono getById(Long id) {
		List<Telefono> telefonos = getHibernateTemplate().find(
				" from Telefono as t" +
				" where t.idTelefono=?", id);
		return telefonos.size()>0?telefonos.get(0):null;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public List<Telefono> getAll() {
		List<Telefono> telefonos = getHibernateTemplate().find(
				" from Telefono as t");
		return telefonos;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional 
	public List<Telefono> getByContacto(final Contacto contacto)
			throws DataAccessException {
		List<Telefono> telefonos = getHibernateTemplate().find(
				"FROM Telefono as t " +
				"WHERE t.contacto = ? ",
				contacto);
		return telefonos;
	}
	
	@Override
	@Transactional
	public void deleteFromContacto(final Contacto contacto) 
			throws DataAccessException {
		List<Telefono> toDelete = getByContacto(contacto);
		getHibernateTemplate().deleteAll(toDelete);
	}

}
